//
//  HttpResponse.m
//  HttpNetWork
//
//  Created by admin on 2019/4/19.
//  Copyright © 2019年 admin. All rights reserved.
//

#import "HttpResponse.h"
#import <IBase/IBase.h>
#import <YYModel/YYModel.h>

@implementation HttpResponse

+ (instancetype)yy_modelWithJSON:(id)json{
    
    HttpResponse* response = [super yy_modelWithJSON:json];
    response.jsondata = json;
    return response;
}

- (NSString*)jsonString{
    return [self.jsondata yy_modelToJSONString];
}


- (void)configError{
    
    _isOK = self.code == 0;
    
    if(!self.isOK){
        switch (self.code) {
            case 501:{
                self.error = [APIError errorWith:authorError info:self.message];
                [Queue async:^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:kTokenExpiredNotification object:NULL userInfo:NULL];
                }];
            }
                break;
            default:
                self.error = [APIError errorWith:apiError info:self.message];
                break;
        }
    }
}

- (HttpResponse*)success:(void (^)(id _Nonnull))success{
    
    [self configError];
    
    if(!self.isOK)
        return self;
    if(success){
        success(self.data);
    }
    return self;
}

- (HttpResponse*)failure:(void (^)(APIError * _Nonnull))failure{
    
    [self configError];
    
    if(self.isOK){
        return self;
    }
    if(failure){
        failure(self.error);
    }
    return self;
    
}

- (HttpResponse*)failureDefalut{
    
    return [self failure:^(APIError * _Nonnull error) {
        if(error.errorInfo.length)
            [Toast toast:error.errorInfo];
        else
            [Toast toast:@"请求失败"];
    }];
}

@end

